#!/usr/bin/env python3
"""
智能图片裁剪系统主程序
基于 Ollama + Qwen2.5-VL:7b 的漫画格式图片标准化处理
"""

import asyncio
import json
import sys
import os
from pathlib import Path
from typing import Dict, List, Any, Optional
import logging
import yaml
from datetime import datetime

# 添加项目根目录到路径
sys.path.append(str(Path(__file__).parent))

from modules.file_scanner import FileScanner
from modules.complete_visual_recognition import CompleteContentRecognition
from modules.cropping_engine import CroppingEngine
# from modules.thread_manager import ThreadManager  # 临时禁用
from modules.config_manager import ConfigManager
from modules.logger import setup_logger

class ImageCroppingSystem:
    """智能图片裁剪系统主类"""
    
    def __init__(self, config_path: str = "config.yaml"):
        """初始化系统"""
        self.config_manager = ConfigManager(config_path)
        self.config = self.config_manager.get_config()
        
        # 设置日志
        self.logger = setup_logger(self.config['logging'])
        
        # 初始化各个模块
        self.file_scanner = FileScanner(self.config)
        self.visual_recognition = CompleteContentRecognition(self.config)
        self.cropping_engine = CroppingEngine(self.config)
        # self.thread_manager = ThreadManager(self.config)  # 临时禁用
        
        self.logger.info("智能图片裁剪系统初始化完成")
    
    async def process_images(self, files: List[Dict[str, Any]], config: Optional[Dict] = None) -> Dict[str, Any]:
        """处理图片列表"""
        if config:
            self.config.update(config)
        
        start_time = datetime.now()
        self.logger.info(f"开始处理 {len(files)} 个图片文件")
        
        try:
            # 1. 文件扫描与预处理
            self.logger.info("步骤 1: 文件扫描与预处理")
            classified_files = await self.file_scanner.scan_and_classify(files)
            
            # 2. 视觉内容识别
            self.logger.info("步骤 2: 视觉内容识别")
            content_regions = await self.visual_recognition.recognize_content(classified_files)
            
            # 3. 智能裁剪
            self.logger.info("步骤 3: 智能裁剪")
            cropped_results = await self.cropping_engine.crop_images(content_regions)
            
            # 4. 生成处理报告
            end_time = datetime.now()
            processing_time = (end_time - start_time).total_seconds()
            
            report = {
                'success': True,
                'total_files': len(files),
                'processed_files': len(cropped_results),
                'processing_time': processing_time,
                'results': cropped_results,
                'timestamp': end_time.isoformat()
            }
            
            self.logger.info(f"处理完成，共处理 {len(cropped_results)} 个文件，耗时 {processing_time:.2f} 秒")
            return report
            
        except Exception as e:
            self.logger.error(f"处理过程中发生错误: {str(e)}")
            return {
                'success': False,
                'error': str(e),
                'timestamp': datetime.now().isoformat()
            }

async def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("Usage: python main.py '<json_data>'")
        sys.exit(1)
    
    try:
        # 解析输入参数
        json_data = json.loads(sys.argv[1])
        files = json_data.get('files', [])
        config = json_data.get('config', {})
        
        # 创建处理系统
        system = ImageCroppingSystem()
        
        # 处理图片
        result = await system.process_images(files, config)
        
        # 输出结果
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
    except Exception as e:
        error_result = {
            'success': False,
            'error': str(e),
            'timestamp': datetime.now().isoformat()
        }
        print(json.dumps(error_result, ensure_ascii=False, indent=2))
        sys.exit(1)

if __name__ == "__main__":
    asyncio.run(main())